package com.xiaoxu.intranetweb.util;


import com.xiaoxu.intranetweb.config.SzConfig;
import org.apache.tomcat.util.http.fileupload.impl.FileSizeLimitExceededException;
import org.apache.velocity.shaded.commons.io.FilenameUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Objects;
import java.util.UUID;

public class FileUploadUtils {

    /**
     * 默认大小 50M
     */
    public static final long DEFAULT_MAX_SIZE = 50 * 1024 * 1024;

    /**
     * 默认的文件名最大长度 100
     */
    public static final int DEFAULT_FILE_NAME_LENGTH = 100;

    /**
     * 以默认配置进行文件上传
     *
     * @param file 上传的文件
     * @return 文件名称
     * @throws Exception
     */

    private static String defaultBaseDir = SzConfig.getProfile();

    public static void setDefaultBaseDir(String defaultBaseDir) {
        FileUploadUtils.defaultBaseDir = defaultBaseDir;
    }

    public static String getDefaultBaseDir() {
        return defaultBaseDir;
    }
    //public static final String upload(MultipartFile file) throws IOException {
    //    try {
    //        return uploadFile(getDefaultBaseDir(), file);
    //    } catch (Exception e) {
    //        throw new IOException(e.getMessage(), e);
    //    }
    //}
    //public static final Boolean delFile(String url) throws IOException {
    //    String filePath = SzConfig.getUploadPath() + StringUtils.substringAfter(url, "upload");
    //    Path path = Paths.get(filePath);
    //    if(Files.exists(path)){
    //        Files.delete(path);
    //        return true;
    //    }
    //    return false;
    //}
    /**
     * 根据文件路径上传
     *
     * @param baseDir 相对应用的基目录
     * @param file    上传的文件
     * @return 文件名称
     * @throws IOException
     */
    public static final String upload(String baseDir, MultipartFile file) throws IOException {
        try {
            return uploadFile(baseDir, file);
        } catch (Exception e) {
            throw new IOException(e.getMessage(), e);
        }
    }

    /**
     * 文件上传
     *
     * @param baseDir          相对应用的基目录
     * @param file             上传的文件
     * @return 返回上传成功的文件名
     * @throws FileSizeLimitExceededException       如果超出最大大小
     * @throws IOException                          比如读写文件出错时
     */
    public static final String uploadFile(String baseDir, MultipartFile file) throws FileSizeLimitExceededException, IOException {;

        String fileName = extractFilename(file);
        String absPath = getAbsoluteFile(baseDir, fileName).getAbsolutePath();
        file.transferTo(Paths.get(absPath));
        return getPathFileName(baseDir, fileName);
    }

    /**
     * 编码文件名
     */
    public static final String extractFilename(MultipartFile file) {
        String fileName = file.getOriginalFilename();
        //fileType
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        String uuid = UUID.randomUUID().toString().replace("-", "");
        return StringUtils.format("{}/{}_{}{}", DateUtils.datePath(), FilenameUtils.getBaseName(file.getOriginalFilename()),uuid,suffix);
    }

    public static final File getAbsoluteFile(String uploadDir, String fileName) throws IOException {
        File desc = new File(uploadDir + File.separator + fileName);

        if (!desc.exists()) {
            if (!desc.getParentFile().exists()) {
                desc.getParentFile().mkdirs();
            }
        }
        return desc;
    }

    public static final String getPathFileName(String uploadDir, String fileName) throws IOException {
        //int dirLastIndex = defaultBaseDir.length() + 1;
        //String currentDir = StringUtils.substring(uploadDir, dirLastIndex);
        //return "/profile" + "/" + currentDir + "/" + fileName;
        return uploadDir + "/" + fileName;
    }

}

